var app = getApp()
var api = require("./API")
var utils = require("./utils")
var commonFields = require("./commonFields")
/**
 * url:请求的url
 * params:请求参数
 * message:loading提示信息
 * success:成功的回调
 * fail:失败的回调
 */
const EXTERNAL_BASE_URL = "https://theory.jiakaoapp.com";
const LAN_URL = "http://192.168.2.143:8017"
const BASE_URL = EXTERNAL_BASE_URL;
const IMAGE_URL = "http://wx.jytjkll.com:8033";

//post请求
function postRequest(url, params, success, fail) {
    this.postRequestLoading(url, params, "", success, fail)
}

//根据判断message 是否显示loading
function postRequestLoading(url, params, message, success, fail) {
    if (message != "") {
        wx.showLoading({
            title: message,
        })
    }
    var requestUrl = "";
    if (url.startsWith("http")) {
        requestUrl = url
    } else {
        requestUrl = BASE_URL + url
    }
    console.log(params)
    if (params) {
    } else {
        params = {}
    }
    let userInfo = utils.getStorageSync(commonFields.userInfo);
    let token = "";
    if (userInfo) {
        token = userInfo.token;
    }
    console.log("httpUtils token", token)
    const postRequestTask = wx.request({
        url: requestUrl,
        data: params,
        header: {
            // 'content-type': 'application/x-www-form-urlencoded'
            'content-type': 'application/json',
            'token': token ? token : "",
        },
        method: 'POST',
        success: function (res) {
            console.log("post 请求成功-url", requestUrl, "请求参数", JSON.stringify(params), "success:", res)
            if (message != "") {
                wx.hideLoading()
            }
            if (res.statusCode == 401) {
                console.log("res.statusCode 清除登录信息")
                try {
                    wx.removeStorageSync(commonFields.userInfo)
                    wx.removeStorageSync(commonFields.userInfo)
                    wx.removeStorageSync(commonFields.isLogin)
                    wx.removeStorageSync(commonFields.mobile)
                } catch (e) {
                    console.log(e)
                } finally {
                    if (url.indexOf(api.API_USER_INFO)) {
                        wx.showModal({
                            title: '提示',
                            content: '请先登录',
                            showCancel: false,
                            success(res) {
                                if (res.confirm) {
                                    wx.switchTab({
                                        url: api.PAGES_MINE_MINE
                                    })
                                } else if (res.cancel) {
                                    wx.reLaunch({
                                        url: api.PAGES_MOCKEXAMS_MOCKEXAMS
                                    })
                                }
                            }
                        })
                    }
                }
                try {
                    success(res.data, res.statusCode)
                } catch (e) {
                    success(res.data)
                }
                return;
            }
            if (res.data && res.data.code == 401) {
                console.log("res.data.code 清除登录信息")
                try {
                    wx.removeStorageSync(commonFields.userInfo)
                    wx.removeStorageSync(commonFields.userInfo)
                    wx.removeStorageSync(commonFields.isLogin)
                    wx.removeStorageSync(commonFields.mobile)
                } catch (e) {
                    console.log(e)
                } finally {
                    if (url.indexOf(api.API_USER_INFO)) {
                        wx.showModal({
                            title: '提示',
                            content: '请先登录',
                            showCancel: false,
                            success(res) {
                                if (res.confirm) {
                                    wx.switchTab({
                                        url: api.PAGES_MINE_MINE
                                    })
                                } else if (res.cancel) {
                                    wx.reLaunch({
                                        url: api.PAGES_MOCKEXAMS_MOCKEXAMS
                                    })
                                }
                            }
                        })
                    }
                }
                try {
                    success(res.data, res.data.code)
                } catch (e) {
                    success(res.data)
                }
                return;
            } else if (res.data && res.data.code != 0) {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'warn',
                    duration: 2000
                })
                return;
            }
            try {
                success(res.data, res.data.code)
            } catch (e) {
                success(res.data)
            }

        },
        fail: function (res) {
            if (message != "") {
                wx.hideLoading()
            }
            console.log("post 请求错误-url", requestUrl, "请求参数:", JSON.stringify(params), "fail:", res)
            fail(res)
        }
    })
}

//get请求
function getRequest(url, params, success, fail) {
    this.getRequestLoading(url, params, "", success, fail)
}

function getRequestLoading(url, params, message, success, fail) {
    if (message != "") {
        wx.showLoading({
            title: message,
        })
    }
    var requestUrl = ""
    if (url.startsWith("http")) {
        requestUrl = url
    } else {
        requestUrl = BASE_URL + url
    }

    let userInfo = utils.getStorageSync(commonFields.userInfo);
    let token = "";
    if (userInfo) {
        token = userInfo.token;
    }
    const getRequestTask = wx.request({
        url: requestUrl,
        data: params,
        header: {
            'Content-Type': 'application/json',
            'token': token,
        },
        method: 'GET',
        success: function (res) {
            if (message != "") {
                wx.hideLoading()
            }
            console.log("get 请求成功-url", requestUrl, "请求参数:", JSON.stringify(params), "success:", res)
            if (res.statusCode == 200) {
                success(res.data)
            } else {
                fail(res)
            }
        },
        fail: function (res) {
            if (message != "") {
                wx.hideLoading()
            }
            console.log("get 请求成功-url", requestUrl, "请求参数:", JSON.stringify(params), "fail:", res)
            fail(res)
        }
    })
}

//取消post请求
function abortPostRequest(url, params, success, fail) {
    postRequestTask.abort()
}

//取消get请求
function abortGetRequest(url, params, success, fail) {
    getRequestTask.abort()
}

function postVipPrice(callback) {
    this.postRequest(api.API_USER_VIP_PRICE, {},
        (res, statusCode) => {
            if (callback) {
                try {
                    callback(res, statusCode)
                } catch (e) {
                    callback(res)
                }
            }
        },
        fail => {

        }
    )
}

function postOrderAdd(params, callback) {
    this.postRequest(api.API_ORDER_ADD, params,
        res => {
            if (callback) {
                callback(res)
            }
        },
        fail => {

        })
}

/**
 * 请求个人信息接口
 * @param callback
 */
function postUserInfo(callback) {
    this.postRequest(api.API_USER_INFO, {},
        (res, statusCode) => {
            console.log("请求UserInfo用户信息状态码", statusCode)
            if (callback) {
                try {
                    callback(res, statusCode)
                } catch (e) {
                    callback(res)
                }
            }
        },
        fail => {
            console.log(fail)
        },
    );
}

/**
 * 账户信息
 * @param callback
 */
function postUserAccount(callback) {
    this.postRequest(api.API_USER_ACCOUNT, {},
        res => {
            if (callback) {
                callback(res)
            }
        }, fail => {
            console.log(fail)
        }
    )
}

function postWithdrawApply(params, callback) {
    this.postRequest(api.API_WITHDRAW_APPLY, params,
        res => {
            if (callback) {
                callback(res)
            }
        },
        fail => {
            console.log(fail)
        })
}

function postWithdrawList(params, callback) {
    this.postRequest(api.API_WITHDRAW_LIST, params,
        res => {
            if (callback) {
                callback(res)
            }
        },
        fail => {
            console.log(fail)
        })
}

/**
 * 我的-考试记录
 * @param callback
 */
function postExamRecords(callback) {
    this.postRequest(api.API_QUESTION_EXAM_HIS, {},
        res => {
            if (callback) {
                callback(res)
            }
        },
        fail => {
            console.log(fail)
        })
}

/**
 * 请求分享二维码
 * @param callback
 */
function postShareQR(callback) {
    this.postRequest(api.API_SHARE_IMG, {},
        res => {
            if (res.code == 0) {
                utils.setStorageSync(commonFields.shareImg, BASE_URL + "/" + res.data.replace("\\", "\/"))
            }
            if (callback) {
                callback(res)
            }
        },
        fail => {
            console.log(fail)
        })
}

/**
 * 退出登录
 * @param callback
 */
function postLogout(callback) {
    this.postRequest(api.API_USER_LOGOUT, {},
        res => {
            if (res.code == 0) {
                wx.showToast({
                    title: '登出成功',
                    duration: 2000,
                })
                utils.removeSotorageByKey(commonFields.userInfo)
                setTimeout(() => {
                    wx.reLaunch({
                        url: api.PAGES_MOCKEXAMS_MOCKEXAMS
                    })
                }, 2000)
            }
            if (callback) {
                callback(res)
            }
        },
        fail => {
            console.log(fail)
        })
}

function postOpenId(js_code, callback) {
    this.postRequest(api.API_USER_OPENID, {
        js_code: js_code
    },
        res => {
            if (callback) {
                callback(res)
            }
        },
        fail => {
            console.log(fail)
        })
}

module.exports = {
    BASE_URL: BASE_URL,
    postRequest: postRequest,
    postRequestLoading: postRequestLoading,
    getRequest: getRequest,
    getRequestLoading: getRequestLoading,
    abortPostRequest: abortPostRequest,
    abortGetRequest: abortGetRequest,
    IMAGE_URL: IMAGE_URL,
    postVipPrice: postVipPrice,
    postOrderAdd: postOrderAdd,
    postUserInfo: postUserInfo,
    postUserAccount: postUserAccount,
    postWithdrawApply: postWithdrawApply,
    postWithdrawList: postWithdrawList,
    postExamRecords: postExamRecords,
    postShareQR: postShareQR,
    postLogout: postLogout,
    postOpenId: postOpenId,
}

